#import "LoginViewController.h"
#import "UserData.h"
#import <AFNetworking/AFNetworking.h>
#import "TabBarViewController.h"
#import "LoginBackView.h"

int state = 0;

@interface LoginViewController ()
@property(nonatomic,strong)UITextField* Account;
@property(nonatomic,strong)UITextField* Password;
@property(nonatomic,strong)UIButton* loginButton;
@property(nonatomic, strong) UIWindow* window;
@property (strong, nonatomic) UIButton *btn;
@property(strong, nonatomic) LoginBackView* bgView;
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"testLoginView");
}

// 定义点击按钮事件
- (void)logIn:(UIButton *)sender {
    self.btn.hidden = true;
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"个人信息";
    self.bgView = nil;
    state = 1;
    [self LoginView];
    
}

// 设置登录按钮
- (void)setLoginButton {
    self.btn = [UIButton buttonWithType:UIButtonTypeSystem];
    self.btn.frame = CGRectMake(0, 0, 140, 140);
    self.btn.center =CGPointMake(self.view.center.x, self.view.center.y);// 设置成水平居中，垂直居中
    self.btn.backgroundColor = [UIColor clearColor]; // 设置为透明
    self.btn.layer.borderColor = [UIColor grayColor].CGColor;
    self.btn.layer.cornerRadius = 70.0;
    self.btn.layer.borderWidth = 1.0;
    [self.btn setTitle:@"登录" forState:UIControlStateNormal];
    self.btn.titleLabel.font = [UIFont systemFontOfSize: 25.0];
    [self.btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.btn addTarget:self action:@selector(logIn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.btn];
}


- (void)Loginbutton:(UIButton*)button {
        NSString* email = [_Account text];
        NSString* pwd = [_Password text];
        NSLog(@"\n %@ \n %@",email,pwd);
        [self logInWithName:email AndPassword:pwd];
}


- (void)logInWithName:(NSString *)name
               AndPassword:(NSString *)password
    {
     NSString *loginURL = @"http://172.18.176.202:3333/hw3/signup";
     NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:name, @"name", password, @"pwd",nil];
    // dictionary To NSJoson
    NSError *err = nil;
    NSData *jasonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&err];
    NSString *jason = [[NSString alloc]initWithData:jasonData encoding:NSUTF8StringEncoding];

    // 登录的接口路径

    loginURL = [loginURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *URL = [NSURL URLWithString:loginURL];

    // 建立一个带协议缓存类型的请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL cachePolicy:0 timeoutInterval:2.0f];
    NSString *contentType = @"application/json";
    [request setValue:contentType forHTTPHeaderField:@"Content-Type"];

    // 设置表单提交的方法
    [request setHTTPMethod:@"post"];

    // 设置要提交的参数
    [request setHTTPBody:[jason dataUsingEncoding:NSUTF8StringEncoding]];

    // 获取返回值
    NSData *recvData =[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:recvData encoding:NSUTF8StringEncoding];
    NSLog(@"%@", jsonString);
    NSError *error = nil;
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:recvData options:NSJSONReadingAllowFragments error:&error];
        
    NSString *ret = [dict objectForKey:@"msg"];
    
    if ([ret isEqual: @"success"]) {
        NSLog(@"request success");
         NSError *err = nil;
         NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"MOSAD", @"name", nil];
         NSData *jasonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&err];
         NSString *jason = [[NSString alloc]initWithData:jasonData encoding:NSUTF8StringEncoding];

         // 个人信息获取的接口路径
         NSString *infoURL = @"http://172.18.176.202:3333/hw3/getinfo";
         infoURL = [infoURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
         NSURL *URL=[NSURL URLWithString:infoURL];

         // 建立一个带协议缓存类型的请求
         NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL cachePolicy:0 timeoutInterval:2.0f];
         NSString *contentType = @"application/json";
         [request setValue:contentType forHTTPHeaderField:@"Content-Type"];

         // 设置表单提交的方法
         [request setHTTPMethod:@"get"];

         // 设置要提交的参数
         [request setHTTPBody:[jason dataUsingEncoding:NSUTF8StringEncoding]];

         // 获取返回值
         NSData *recvData =[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
         NSString *jsonString = [[NSString alloc] initWithData:recvData encoding:NSUTF8StringEncoding];
         NSLog(@"%@", jsonString);
         NSError *error = nil;
         NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:recvData options:NSJSONReadingAllowFragments error:&error];
        
         NSDictionary *userData = dict;
         [UserData LoadData:userData];
            UIWindow* window = nil;
            if (@available(iOS 13.0, *))
            {
                for (UIWindowScene* windowScene in [UIApplication sharedApplication].connectedScenes)
                    if (windowScene.activationState == UISceneActivationStateForegroundActive)
                    {
                        window = windowScene.windows.firstObject;
                        break;
                    }
            }
            else
            {
                window = [UIApplication sharedApplication].keyWindow;
            }
            window.rootViewController = [[TabBarViewController alloc]init];
    } else {
        NSLog(@"request failure");
    }
        
    }

- (void)Alert:(NSString *)msg
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                       message:msg
                                                                preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:true completion:nil];
    }

- (void)LoginView {
    _Account=[[UITextField alloc]initWithFrame:CGRectMake(20,200,self.view.frame.size.width-40,50)];
    _Account.backgroundColor=[UIColor clearColor];
    _Account.placeholder= [NSString stringWithFormat:@" Username"];
    _Account.layer.borderWidth = 1.5f;//边框大小
    _Account.layer.cornerRadius = 5;//边框圆角大小//设置占位字的颜色
    _Account.layer.borderColor = [UIColor whiteColor].CGColor;//边框颜色
    [self.view addSubview:_Account];
    
    _Password = [[UITextField alloc]initWithFrame:CGRectMake(20,260,self.view.frame.size.width-40,50)];
    _Password.backgroundColor=[UIColor clearColor];
    _Password.placeholder=[NSString stringWithFormat:@" Password"];
    [_Password setSecureTextEntry:YES];
    _Password.layer.borderWidth = 1.5f;//边框大小
    _Password.layer.cornerRadius = 5;//边框圆角大小//设置占位字的颜色
    _Password.layer.borderColor = [UIColor whiteColor].CGColor;//边框颜色
    [self.view addSubview:_Password];
    
    _loginButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [_loginButton setFrame:CGRectMake(20,320,self.view.frame.size.width-40,50)];
    [_loginButton setTitle:@"Login"forState:UIControlStateNormal];
    [_loginButton setBackgroundColor:[UIColor colorWithRed:51/255.0 green:102/255.0 blue:255/255.0 alpha:1]];
    [_loginButton setTitleColor:[UIColor whiteColor]forState:UIControlStateNormal];
    [_loginButton addTarget:self
                     action:@selector(Loginbutton:) forControlEvents:UIControlEventTouchUpInside];
    _loginButton.layer.masksToBounds = YES; //允许绘制

    _loginButton.layer.cornerRadius = 4;//边框弧度

    _loginButton.layer.borderWidth = 1; //边框的宽度

    [self.view addSubview:_loginButton];
}

- (void)viewWillAppear:(BOOL)animated {
    self.btn.hidden = true;
//        [self setBackgroundColor];
    self.navigationItem.title = @"我的";
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:self.view.bounds];
    imageView.image=[UIImage imageNamed:@"back"];
    [self.view insertSubview:imageView atIndex:0];
    [self setLoginButton];
}

@end
